package com.yujing.yview

import android.app.Activity
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.text.method.DigitsKeyListener
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import com.yujing.yview.base.YBaseDialog
import com.yujing.yview.contract.YSuccessFailListener

import com.yujing.yview.databinding.DialogSetIpPortBinding
import com.yujing.yview.utils.YCheck

/**
 * IP端口对象
 * @author yujing 2020年6月12日15:07:12
 */
data class IpPort(
    var Ip: String,
    var Port: String
)

/**
 * 设置IP对话框
 * @author yujing 2020年12月24日10:31:00
 */
/*用法
val ySetIpDialog = YSetIpDialog(this)
ySetIpDialog.uesNumberKeyboard=true
ySetIpDialog.setYSuccessFailListener(object : com.yujing.yview.contract.YSuccessFailListener<IpPort?, String?> {
    override fun success(success: IpPort?) {
        val ip = success?.Ip.toString()
        val port = success?.Port.toString()
        textView1.text = "您设置的IP是：$ip 端口是：$port"
    }
    override fun fail(fail: String?) {
        fail?.let { speak(it) }
    }
})
ySetIpDialog.defaultIP = "192.168.6.9"
ySetIpDialog.defaultPort = "8080"
ySetIpDialog.show()
 */
class YSetIpDialog(activity: Activity) : YBaseDialog<DialogSetIpPortBinding>(activity, R.layout.dialog_set_ip_port) {
    init {
        fullscreen = true
        widthPixels = 0.4F
        heightPixels = 0.6F
        fillColor = ContextCompat.getColor(activity, R.color.fill_background)
    }

    var defaultIP: String? = null
    var defaultPort: String? = null

    // 是否启用数字软键盘
    var uesNumberKeyboard = false

    //如启用小键盘每次按键监听
    var inputKeYListener1: ((String?) -> Unit)? = null

    private var ySuccessFailListener: YSuccessFailListener<IpPort?, String?>? = null

    var btNameOK = "确　定"
    var btNameCancel = "取　消"

    //文字大小比例
    var textSizeScale: Float = 1.0F

    //类型，1：ip和端口，2：url和端口
    var type = 1

    //初始化完成
    var initCompleteListener: ((DialogSetIpPortBinding) -> Unit)? = null

    //确定事件
    fun confirm() {
        val ip: String = binding.etIp.text.toString()
        val port: String = binding.etPort.text.toString()
        if (!checkIpPort(ip, port)) {
            return
        }
        ySuccessFailListener?.success(IpPort(ip, port))
        dismiss()
    }

    override fun init() {
        //设置默认值
        if (defaultIP != null)
            binding.etIp.setText(defaultIP)
        if (defaultPort != null)
            binding.etPort.setText(defaultPort)

        if (type == 1) {
            binding.tilIp.hint = "请输入IP"
            //android:digits="0123456789."
            binding.etIp.inputType = EditorInfo.TYPE_NUMBER_FLAG_DECIMAL
            binding.etIp.keyListener = DigitsKeyListener.getInstance("0123456789.")
        } else if (type == 2) {
            binding.tilIp.hint = "请输入地址"
        }

        binding.etIp.setSelection(binding.etIp.text.toString().length)
        binding.btConfirm.text = btNameOK
        binding.btCancel.text = btNameCancel
        //确定按钮监听
        binding.btConfirm.setOnClickListener {
            confirm()
        }
        //取消按钮监听
        binding.btCancel.setOnClickListener { dismiss() }
        //ip获取焦点
        view.post { binding.etIp.requestFocus() }

        //启用数字软键盘
        if (uesNumberKeyboard) {
            //点击不弹出输入法
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                binding.etIp.showSoftInputOnFocus = false
            //点击不弹出输入法
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                binding.etPort.showSoftInputOnFocus = false

            //如果是启用数字软键盘，光标后移
            binding.etIp.addTextChangedListener(MyTextWatcher(binding.etIp))
            binding.etPort.addTextChangedListener(MyTextWatcher(binding.etIp))

            binding.etIp.setOnClickListener {
                val numberKeyboard = NumberKeyboard(activity, false, NumberKeyboard.Type.STRING)
                numberKeyboard.title = "请输入IP"
                numberKeyboard.defaultString = binding.etIp.text.toString()
                numberKeyboard.listener = { s -> binding.etIp.setText(s) }
                numberKeyboard.inputKeYListener1 = { s ->
                    inputKeYListener1?.invoke(
                        s
                    )
                }
                numberKeyboard.show()
            }
            binding.etPort.setOnClickListener {
                val numberKeyboard = NumberKeyboard(activity, false, NumberKeyboard.Type.STRING)
                numberKeyboard.title = "请输入端口"
                numberKeyboard.defaultString = binding.etPort.text.toString()
                numberKeyboard.listener = { s -> binding.etPort.setText(s) }
                numberKeyboard.inputKeYListener1 = { s ->
                    inputKeYListener1?.invoke(
                        s
                    )
                }
                numberKeyboard.show()
            }
        }
        //---------------------------缩放---------------------------
        //设置文字放大缩小倍数
        binding.tvTitle.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        binding.etIp.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        binding.etPort.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        binding.btCancel.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        binding.btConfirm.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        //输入框高度缩放
        binding.etIp.also {
            val lp = it.layoutParams
            lp.height = (lp.height * textSizeScale).toInt()
            it.layoutParams = lp
        }
        binding.etPort.also {
            val lp = it.layoutParams
            lp.height = (lp.height * textSizeScale).toInt()
            it.layoutParams = lp
        }
        //按钮高度缩放
        binding.llBt.also {
            val lp = it.layoutParams
            lp.height = (lp.height * textSizeScale).toInt()
            it.layoutParams = lp
        }
        //---------------------------缩放---------------------------
        initCompleteListener?.invoke(binding)
    }

    fun setYSuccessFailListener(ySuccessFailListener: YSuccessFailListener<IpPort?, String?>) {
        this.ySuccessFailListener = ySuccessFailListener
    }

    //检查ip和端口
    private fun checkIpPort(ip: String, port: String): Boolean {
        if (type == 1) {
            if (ip.isEmpty()) {
                ySuccessFailListener?.fail("请输入IP")
                return false
            }
            if (!YCheck.isIPv4(ip)) {
                ySuccessFailListener?.fail("IP不符合规范")
                return false
            }
        } else if (type == 2) {
            if (ip.isEmpty()) {
                ySuccessFailListener?.fail("请输入地址")
                return false
            }
        }

        if (port.isEmpty()) {
            ySuccessFailListener?.fail("请输入端口")
            return false
        }

        if (!YCheck.isPort(port)) {
            ySuccessFailListener?.fail("端口不符合规范")
            return false
        }
        return true
    }
}


//如果是启用数字软键盘，光标移动到最后
private class MyTextWatcher(var textView: com.google.android.material.textfield.TextInputEditText) :
    TextWatcher {
    override fun afterTextChanged(s: Editable?) {}

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        textView.setSelection(textView.length())
    }
}